package com.cj.job;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.listener.PatternTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;
import org.springframework.stereotype.Component;
import com.cj.util.RedisObject;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;

@Component
public class Sub extends MessageListenerAdapter{
	
	@Autowired
	RedisTemplate<String, String> redisTemplate;
	
	@Autowired
	RedisObject redisObject;
	
	@Bean
	RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory,
	                                        MessageListenerAdapter listenerAdapter) {
	    RedisMessageListenerContainer container = new RedisMessageListenerContainer();
	    container.setConnectionFactory(connectionFactory);
	    container.addMessageListener(listenerAdapter, new PatternTopic("news"));
	    container.addMessageListener(listenerAdapter, new PatternTopic("news"));//配置要订阅的订阅项
	    return container;
	}
	String channel="news";
	int newCache_Time=-200;//假设新闻缓存是200秒
	String newsCache_key = "newscache";//保存新闻时间戳的key
	@Override
	public void onMessage(Message message, byte[] pattern) {

		if("cc".equals(message.toString())){
			clearNewsCache();
		}
		System.out.println(message);
	}
	
	public void clearNewsCache(){//获取过期的 id们
		DateTime redisDate = DateUtil.offsetSecond(DateUtil.date(), newCache_Time);//当前 时间戳 -200秒
		List<String> list = new ArrayList<String>();
		Set<String> redisKey = redisTemplate.opsForZSet().range(newsCache_key, 0, -1);//找到Zset集合的所有field
		for (String keyTime : redisKey) {
			Date lastTime = DateUtil.parse(keyTime);//之前设置的时间戳
			if(DateUtil.between(redisDate,lastTime,  DateUnit.MS, false)<=0) {//过期了
				//找到过期的key
				list.add(keyTime);
				System.out.println("需要删除的过期KEY" + keyTime);
			}
		}
		if(list == null || list.size()<=0) {
			System.out.println("no expired news");
		}else {
			redisObject.multiExec(redisTemplate, list);//执行删除命令
			System.out.println("clear news cache done~~~");
		}
		
		
		
		
		
		
		
		
		
	}
	
	
	
	
	

}
